const express = require('express')
const db = require('../db/db')
const expect = require('../extensions/expect')
const filter = require('../extensions/filter')


const router = express.Router()


router.get('/ask', filter.signin, (req, res) => {
    db.Keyword.list()
        .then(keywords => {
            res.render('ask', { keywords })
        })
        .catch(err => {
            res.pageError(err)
        })
})


router.post('/api/keyword/add', filter.signin, (req, res) => {
    new db.Keyword.Model({
        text: req.body.text,
        createUser: req.cookies.user.id,
        createTime: new Date(),
        ip: db.formatIP(req.ip)
    })
        .save()
        .then(() => {
            res.apiSuccess('添加关键词成功！')
        })
        .catch(err => {
            if (db.isDuplicateIndexError(err)) {
                res.apiMessage('关键词重复！')
            }
            else if (err && err.errors && err.errors.text) {
                res.apiMessage(err.errors.text.message)
            }
            else {
                res.apiError(err)
            }
        })
})


router.post('/api/ask/add', filter.signin, (req, res) => {
    new db.Question.Model({
        text: req.body.text,
        keyword: req.body.keyword,
        createUser: req.cookies.user.id,
        createTime: new Date(),
        ip: db.formatIP(req.ip)
    })
        .save()
        .then(() => {
            res.apiSuccess('添加问题成功！')
        })
        .catch(err => {
            if (err && err.errors) {
                if (err.errors.text) {
                    res.apiMessage(err.errors.text.message)
                }
                else if (err.errors.keyword) {
                    res.apiMessage(err.errors.keyword.message)
                }
            }
            else {
                res.apiError(err)
            }
        })
})


router.post('/api/ask/remove/:id', filter.signin, (req, res) => {
    db.Question.Model.findById(req.params.id)
        .then(m => {
            expect(m).not.toBeNull().error('要删除的问题不存在！')

            var hasPermission = m.createUser == req.cookies.user.id || req.cookies.user.account == 'admin'
            expect(hasPermission).toBe(true).error('没有删除这个问题的权限！')

            var ans = db.Answer.Model.remove({ _id: { $in: m.answers } }).exec()
            var q = db.Question.Model.remove({ _id: m._id }).exec()

            return Promise.all([ans, q])
        })
        .then(m => {
            res.apiSuccess('删除问题成功！')
        })
        .catch(err => {
            res.apiError(err)
        })
})


module.exports = router
